package com.ckjava.test.gencode.component;

import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

@Component
public class TemplateCom {

    private static Logger logger = LoggerFactory.getLogger(TemplateCom.class);

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    public String renderTempalte(String template, Map<String, Object> dataMap) {
        try {
            Template tpl = freeMarkerConfigurer.getConfiguration().getTemplate(template);
            return FreeMarkerTemplateUtils.processTemplateIntoString(tpl, dataMap);
        } catch (Exception e) {
            logger.error(this.getClass().getName().concat(".render has error"), e);
            return null;
        }

    }

    public String renderString(String template, Map<String, Object> dataMap) {
        try {
            StringWriter result = new StringWriter();
            Template t = new Template("name", new StringReader(template), freeMarkerConfigurer.getConfiguration());
            t.process(dataMap, result);
            return result.toString();
        } catch (Exception e) {
            logger.error(this.getClass().getName().concat(".render has error"), e);
            return null;
        }

    }
}
